import axios, { AxiosRequestConfig } from 'axios'
import { message as $message } from 'antd'
import { apiHost } from 'public/config'

// const host = apiHost
// const host = '//118.178.90.188:50055'
// const host = '//15.75.21.19:9081'
const host = '//15.75.10.165:9081'

axios.defaults.timeout = 6000

axios.interceptors.request.use(
  config => {
    return config
  },
  error => {
    Promise.reject(error)
  }
)

axios.interceptors.response.use(
  config => {
    if (config.data.error) {
      const errMessgae = config.data.message
      $message.error(errMessgae)
      return config.data.code !== '000202' ? config.data : Promise.reject(errMessgae)
      // return $message.error(config.data.message)
    }
    if (config?.data?.message) {
      // $message.success(config.data.message)
    }
    return config?.data
  },
  error => {
    let errorMessage = '网络错误'
    if (error?.message?.includes('Network Error')) {
      errorMessage = '网络错误，请检查您的网络'
    }
    console.dir(error)
    error.message && $message.error(errorMessage)
    window.localStorage.removeItem('u')
    return {
      status: false,
      message: errorMessage,
      result: null
    }
  }
)

export type Response<T = any> = {
  status: boolean
  message: string
  result: T
}

type Method = 'get' | 'post' | 'delete'

export type MyResponse<T = any> = Promise<Response<T>>

/**
 *
 * @param method - request methods
 * @param url - request url
 * @param data - request data or params
 */
export const request = <T = any>(
  method: Method,
  url: string,
  data?: any,
  config?: AxiosRequestConfig,
  isRemoveToken?: boolean
): MyResponse<T> => {
  url = host + url
  const resultConfig = isRemoveToken
    ? config
    : {
        ...config,
        headers: {
          'x-token': JSON.parse(localStorage.getItem('u')!) ? JSON.parse(localStorage.getItem('u')!).token : ''
        }
      }
  if (method === 'post') {
    return axios.post(url, data, resultConfig)
  } else {
    return axios.get(url, {
      params: data,
      ...resultConfig
    })
  }
}
